<template>
  <div>
    <!-- 员工弹框 -->
    <el-dialog
      :title="form.id? '编辑员工':'新增员工'"
      :visible="dialogVisible"
      @close="closeFn"
    >
      <el-form ref="form" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="员工名称" prop="username">
          <el-input v-model="form.username" style="width:80%" />
        </el-form-item>
        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="form.email" style="width:80%" />
        </el-form-item>
        <!--v-if绑定一个show变量 -->
        <el-form-item v-if="show" label="员工密码" prop="password">
          <el-input v-model="form.password" style="width:80%" />
        </el-form-item></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="closeFn">取 消</el-button>
        <el-button type="primary" plain size="small" @click="confrim">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addEmployees, editEmployees } from '@/api/employees'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 设置初始值为默认显示
    show: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      form: {
        username: '',
        email: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入员工名称', trigger: 'blur' }
        ],
        email: [{ required: true, message: '请输入员工邮箱', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 新增在dialog可以实现效果，但刷新页面需子传父
    async confrim() {
      await this.$refs.form.validate(async(valid) => {
        // 校验成功
        if (valid) {
          if (this.form.id) {
            // 注意注意
            await editEmployees(this.form)
          } else {
            // 新增
            await addEmployees(this.form)
          }
          this.closeFn()
          // 子组件直接调用
          // GetEmployeesList()为父组件更新数据所调用的函数-----此步是刷新页面
          this.$parent.GetEmployeesList()
        }
        // 校验失败
        else {
          console.log('error submit!!')
          return false
        }
      })
    },
    closeFn() {
      this.$refs.form.resetFields()
      // 关闭弹窗
      this.$emit('update:dialogVisible', false)
      // 清空表单
      this.form = {
        username: '',
        email: '',
        password: ''
      }
    }
  }
}
</script>

<style lang='scss' scoped>

</style>
